﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZYSocket.share;
using CSM.Lib.Protocol;

namespace CSM.Client
{
	/// <summary>
	/// 登入界面
	/// </summary>
	public partial class UserLoginForm : Form
	{
		/// <summary>
		/// 登入成功为TRUE
		/// </summary>
		public bool Logins { get; set; }
		public UserInfoResp UserInfo;

		public UserLoginForm()
		{
			//注册数据包输入事件
			SocketManager.DataInput += new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
			InitializeComponent();
			//测试关闭事件
			this.Closed += new EventHandler(LogOn_Closed);
			Logins = false;
		}

		void LogOn_Closed(object sender, EventArgs e)
		{
			//删除数据包输入事件
			SocketManager.DataInput -= new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
		}

		/// <summary>
		/// 输入包输入处理
		/// </summary>
		/// <param name="Data"></param>
		void SocketManager_DataInput(byte[] Data)
		{
			#region 解析data，同时输出p
			ProtocolBase[] p = null;
			try
			{
				p = Protocol.Decoder(Data, SocketManager.BuffListManger);
			}
			catch(Exception)
			{
				//Console.WriteLine(((UserInfo)buffer.Tag).NickName + ": " + ex.Message + "\n" + ex.StackTrace);
			}
			#endregion

			#region 处理每一个p
			if (p != null)
			{
				foreach (ProtocolBase item in p)
				{
					switch (item.Type)
					{
						case ProtocolWord.UserLoginResp:
							{
								UserLoginResp resp = p[0] as UserLoginResp;

								if (resp.Result == 1) //1登入失败
									MessageBox.Show(resp.Message);
								else if (resp.Result == 2) //2登入成功
								{
									Logins = true; //设置 LOGINS

									UserInfoReq temp = new UserInfoReq(); //发送一个登入数据包

									SocketManager.client.SendTo(Protocol.Encoder(temp));
								}
							}
							break;
						case ProtocolWord.UserInfoResp:
							{

								this.BeginInvoke(new EventHandler((o, x) => Close()));  //关闭窗口
							}
							break;
					}
				}
			}
			#endregion
       }

		private void button1_Click(object sender, EventArgs e)
		{
			UserLoginReq temp = new UserLoginReq() //发送一个登入数据包
			{
				ReqType = UserLoginReq.LoginReqType.NickName,
				LoginKey = this.textBox1.Text,
				Password = this.textBox2.Text
			};

			SocketManager.client.SendTo(Protocol.Encoder(temp));
		}

		private void button2_Click(object sender, EventArgs e)
		{
			Close();
		}
	}
}
